﻿using System;
using SPPropertyBagManagement.Code;

namespace SPPropertyBagManagement.Layouts.SPPropertyBagManagement
{
    public partial class PropertiesEdit : PropertyManagementBasePage
    {
        /// <summary>
        /// Represents the method that handles the Init event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (!IsPostBack)
            {
                LoadProperties();
            }

            SetPageTitle("Edit " + Scope + " Properties");
            SetPageSubTitle(Scope + " Properties Management");

            btnAddNewProp.NavigateUrl = "javascript:openNewPropertyDialog('" + Scope + "','" + ObjectId + "','" + ListItemObjectId + "');";
            editPropertyMenuItem.ClientOnClickNavigateUrl = "javascript:openSingleEditDialog('%PROPERTYID%','" + Scope + "','" + ObjectId + "','" + ListItemObjectId + "');";
            deletePropertyMenuItem.ClientOnClickNavigateUrl = "javascript:openDeleteDialog('%PROPERTYID%','" + Scope + "','" + ObjectId + "','" + ListItemObjectId + "');";
        }

        /// <summary>
        /// Loads the properties.
        /// </summary>
        private void LoadProperties()
        {
            var properties = PropertyManager.GetProperties(Scope, ObjectId, ListItemObjectId);

            properties.RemoveAll(x => !x.IsPropertyNameSupported);
            properties.RemoveAll(x => !x.IsPropertyValueSupported);

            grdMain.DataSource = properties;
            grdMain.DataBind();
        }

        /// <summary>
        /// Handles the OnClick event of the btnExport control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        protected void btnExport_OnClick(object sender, EventArgs e)
        {
            var data = PropertyManager.GetPropertiesAsXML(Scope, ObjectId, ListItemObjectId);
            Utils.DownloadFileToClient(Page, data, "properties.txt");
        }
    }
}
